var request = require('request'),
	cheerio = require('cheerio'),
	baseUrl = 'http://www.streetinsider.com/rating_history.php?q={0}',
	ticker = process.argv[2],
	url = baseUrl.replace('{0}', ticker),
	headers = {
		'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0'
	};

request.get({ url: url, headers: headers }, function (err, resp, body)
{
	var $ = cheerio.load(body),
		$table = $($('table').get(0)),
		$trs = $table.find('tr.LiteHover'),
		opinions = [],
		opinionsString;

	$trs.each(function (i, tr)
	{
		var $tds = $(tr).find('td'),
			opinion = {
				Date: $($tds.get(0)).text(),
				Firm: $($tds.get(1)).find('a').text(),
				Action: $($tds.get(2)).find('span').text(),
				Current: cutBrackets($($tds.get(3)).text()),
				Previous: cutBrackets($($tds.get(3)).find('span').text()),
				PriceTarget: parseFloat(parseInt($($tds.get(4)).text()))
			},
			updateDate = $($($tds.get(1)).find('a').get(1)).text(),
			tokens;
			
		if (updateDate) {
			tokens = updateDate.split(' ');
			if (tokens && tokens.length > 0) {
				opinion.Date = tokens[tokens.length - 1];
			}
		}

		if (!opinion.Date && !opinion.Current)
		{
			return;
		}

		opinions.push(opinion);
	});

	opinionsString = JSON.stringify(opinions);
	console.log(opinionsString);
});

function cutBrackets(input)
{
	if (input.indexOf('(') >= 0)
	{
		return input.substring(0, input.indexOf('(') - 1);
	}

	return input;
}